package com.frxuexi.mymvi

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class NewsViewModel @Inject constructor(private val newsRepository: NewsRepository):ViewModel() {

    //存放意图的管道
    val channel= Channel<NewsIntent>(Channel.UNLIMITED)

    //可变的状态，用于更新UI
    private var _state= MutableStateFlow<NewsState>(NewsState.onLoading)
        val state:StateFlow<NewsState>
            get() = _state


    init {
        viewModelScope.launch {
            //ViewModel接收意图并处理意图
            channel.receiveAsFlow().collect{
                when(it){
                    is NewsIntent.getNews->{
                        getMyNews(it.page)
                    }
                }
            }
        }
    }

    fun getMyNews(page:Int){
        viewModelScope.launch {
//            3.请求网络-结果放入State
            newsRepository.getNews(page)
                .flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }
                .collect{
                    if(it.code==0){
                        _state.value=NewsState.onSuccess(it.data.records)
                    }else{
                        _state.value=NewsState.onError(it.msg)
                    }
                }
        }
    }

}